package com.book.controller.borrow;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.core.util.ExcelUtil;
import com.book.core.domain.Books;
import com.book.core.domain.BorrowRecords;
import com.book.core.dto.ReaderBorrowBookDTO;
import com.book.core.mode.LineBarChart;
import com.book.core.mode.R;
import com.book.core.query.BorrowRecordQuery;
import com.book.core.vo.PageVO;
import com.book.core.vo.ReadingStarVO;
import com.book.listener.GenericExcelDataListener;
import com.book.service.BorrowRecordsService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/borrow-record")
@RequiredArgsConstructor
public class BorrowRecordsController {
    private final BorrowRecordsService borrowRecordsService;

    @PostMapping("/borrow")
    public R borrowBook(@RequestBody @Validated ReaderBorrowBookDTO dto) {
        return borrowRecordsService.newBorrowBook(dto);
    }

    @PutMapping("/return")
    public R returnBook(@RequestBody List<Long> recordIds) {
        return borrowRecordsService.returnBook(recordIds);
    }

    @PostMapping
    public R save(@RequestBody @Validated BorrowRecords borrowRecords) {
        borrowRecordsService.save(borrowRecords);
        return R.ok();
    }
    @PutMapping
    public R update(@RequestBody @Validated  BorrowRecords borrowRecords) {
        borrowRecordsService.updateById(borrowRecords);
        return R.ok();
    }

    @GetMapping("/page")
    public R<PageVO<BorrowRecords>> getBorrowRecordPage(BorrowRecordQuery query) {
        return R.ok(borrowRecordsService.getBorrowRecordPage(query));
    }

    @PostMapping("/renew")
    public R renewBook(@RequestBody @Validated List<Long> dto) {
        return borrowRecordsService.renewBook(dto);
    }

    @GetMapping("/statistic")
    public R getBorrowStatisticByTimeRange(@RequestParam String range) {
        LineBarChart chartData = borrowRecordsService.getBorrowStatisticByTimeRange(range);
        return R.ok(chartData);
    }
    @GetMapping("/reading-star")
    public R<List<ReadingStarVO>> getReadingStar() {
        List<ReadingStarVO> starList = borrowRecordsService.getReadingStar();
        return R.ok(starList);
    }
    @GetMapping("/export")
    public void exportBookExcel(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        ExcelUtil.setExcelResponseHeader(response, "借阅列表");
        // 2. 分页查询数据（避免内存溢出）
        int pageSize = 1000; // 每页1000条
        int pageNum = 1;
        boolean hasNext = true;
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .head(BorrowRecords.class)
                .excelType(ExcelTypeEnum.XLSX)
                .build();
        WriteSheet writeSheet = EasyExcel.writerSheet("借阅列表").build();
        // 3. 分批写入Excel
        while (hasNext) {
            List<BorrowRecords> batchList = borrowRecordsService.lambdaQuery().page(new Page<>(pageNum, pageSize)).getRecords();
            if (batchList.isEmpty()) {
                hasNext = false;
            } else {
                excelWriter.write(batchList, writeSheet);
                pageNum++;
            }
        }
        excelWriter.finish();
    }
    @PostMapping("/import")
    public R<String> importBookExcel(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Books.class, new GenericExcelDataListener<BorrowRecords>(borrowRecordsService)).sheet().doRead();
        return R.ok("导入成功",null);
    }
}
